#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
管理员Token生成工具
用于生成管理员用户的JWT token
"""

import sys
from datetime import timedelta
from app import create_app
from app.models.admin import Admin
from flask_jwt_extended import create_access_token

def generate_admin_token(username='admin', days=7):
    """生成管理员token"""
    app = create_app('development')
    with app.app_context():
        admin = Admin.query.filter_by(username=username).first()
        if admin and admin.is_active:
            # 生成长期有效的token
            access_token = create_access_token(
                identity=f"admin:{admin.id}",
                expires_delta=timedelta(days=days)
            )
            return admin, access_token
        else:
            return None, None

def main():
    username = sys.argv[1] if len(sys.argv) > 1 else 'admin'
    days = int(sys.argv[2]) if len(sys.argv) > 2 else 7
    
    admin, token = generate_admin_token(username, days)
    
    if admin and token:
        print(f"✅ 管理员Token生成成功!")
        print(f"管理员: {admin.username} (ID: {admin.id})")
        print(f"有效期: {days}天")
        print(f"Token: {token}")
        print("\n📋 使用方法:")
        print(f"Authorization: Bearer {token}")
    else:
        print(f"❌ 管理员 '{username}' 不存在或已被禁用")

if __name__ == '__main__':
    main() 